package com.bw.controller;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.lang.tree.Tree;
import cn.hutool.core.lang.tree.TreeNodeConfig;
import cn.hutool.core.lang.tree.TreeUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.bw.common.ResultModel;
import com.bw.config.Result;
import com.bw.domain.SysDept;
import com.bw.service.SysDeptService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.Comparator;
import java.util.Date;
import java.util.List;

/**
 * @author 13096
 */
@RestController
@RequestMapping("/dept")
public class DeptController {
    @Autowired
    SysDeptService deptService;
    @Autowired
    HttpServletRequest request;
    @GetMapping("/deptList")
    public List<Tree<String>> deptList() {
        LambdaQueryWrapper<SysDept> wrapper = new LambdaQueryWrapper<>();
        wrapper.orderByAsc(SysDept::getParentId, SysDept::getOrderNum);
        wrapper.eq(SysDept::getDelFlag,"0");
        List<SysDept> list = deptService.list(wrapper);
        //配置
        TreeNodeConfig treeNodeConfig = new TreeNodeConfig();
        //转换器 (含义:找出父节点为字符串零的所有子节点, 并递归查找对应的子节点, 深度最多为 3)
        List<Tree<String>> treeNodes = TreeUtil.build(list, "0", treeNodeConfig,
                (treeNode, tree) -> {
                    tree.setId(treeNode.getDeptId() + "");
                    tree.setParentId(treeNode.getParentId() + "");
                    // 扩展属性 ...
                    tree.putExtra("deptName", treeNode.getDeptName());
                });
        return treeNodes;
    }

    /**
     * 获取部门列表
     * @return
     */
    @RequestMapping("/parentName")
    public ResultModel parentName(){
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("status","0");
        // 展示未删除的数据
        queryWrapper.eq("del_flag","0");
        // 给列表进行排序
        queryWrapper.orderByAsc("parent_id","order_num");
        List<SysDept> deptList =  deptService.list(queryWrapper);
        // 配置
        TreeNodeConfig treeNodeConfig = new TreeNodeConfig();
        // 最大递归深度
        treeNodeConfig.setDeep(3);
        // 动态生成树状结构父节点
        String rootId = "0";
        if(null == deptList || deptList.size() == 0){
            // 当查询的列表为空时,展示带查询条件的列表
            return ResultModel.successed(deptService.list(queryWrapper));
        }
        for (SysDept dept : deptList) {
            if("0".equals(dept.getParentId())){
                break;
            }else {
                rootId = String.valueOf(dept.getParentId());
                System.out.println("父节点id:" + rootId);
                break;
            }
        }
        // 转换器 (含义:找出父节点为字符串rootId的值的所有子节点, 并递归查找对应的子节点, 深度最多为 3)
        List<Tree<String>> treeNodes = TreeUtil.build(deptList, rootId, treeNodeConfig,
                (treeNode, tree) -> {
                    tree.setId(treeNode.getDeptId() + "");
                    // 部门名称
                    tree.setName(treeNode.getDeptName());
                    tree.setParentId(treeNode.getParentId() + "");
                    // 根据权重排序
                    tree.setWeight(treeNode.getOrderNum());
                    // 扩展属性 ...
                    tree.putExtra("label", treeNode.getDeptName());
                    tree.putExtra("value", treeNode.getDeptId());
                });
        System.out.println(treeNodes + "+++++++++");
        return ResultModel.successed(treeNodes);
    }

    /**
     * 树形结构列表
     * @param sysDept
     * @return
     */
    @RequestMapping("/list")
    public ResultModel list(@RequestBody SysDept sysDept){
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.like(StrUtil.isNotEmpty(sysDept.getDeptName()),"dept_name",sysDept.getDeptName());
        queryWrapper.eq(StrUtil.isNotEmpty(sysDept.getStatus()),"status",sysDept.getStatus());
        // 展示未删除的数据
        queryWrapper.eq("del_flag","0");
        // 给列表进行排序
        queryWrapper.orderByAsc("parent_id","order_num");
        List<SysDept> deptList =  deptService.list(queryWrapper);
        // 配置
        TreeNodeConfig treeNodeConfig = new TreeNodeConfig();
        // 最大递归深度
        treeNodeConfig.setDeep(3);
        // 动态生成树状结构父节点
        String rootId = "0";
        if(null == deptList || deptList.size() == 0){
            // 当查询的列表为空时,展示带查询条件的列表
            return ResultModel.successed(deptService.list(queryWrapper));
        }
        for (SysDept dept : deptList) {
            if("0".equals(dept.getParentId())){
                break;
            }else {
                rootId = String.valueOf(dept.getParentId());
                System.out.println("父节点id:" + rootId);
                break;
            }
        }
        // 转换器 (含义:找出父节点为字符串rootId的值的所有子节点, 并递归查找对应的子节点, 深度最多为 3)
        List<Tree<String>> treeNodes = TreeUtil.build(deptList, rootId, treeNodeConfig,
                (treeNode, tree) -> {
                    tree.setId(treeNode.getDeptId() + "");
                    // 部门名称
                    tree.setName(treeNode.getDeptName());
                    tree.setParentId(treeNode.getParentId() + "");
                    // 根据权重排序
                    tree.setWeight(treeNode.getOrderNum());
                    // 扩展属性 ...
                    tree.putExtra("deptName", treeNode.getDeptName());
                    tree.putExtra("orderNum", treeNode.getOrderNum());
                    tree.putExtra("status", treeNode.getStatus());
                    // 前端时间格式化处理
                    String format = DateUtil.format(treeNode.getCreateTime(), "yyyy-MM-dd HH:mm:ss");
                    tree.putExtra("createTime", format);
                });
        System.out.println(treeNodes + "-----------------");
        return ResultModel.successed(treeNodes);
    }


    /**
     * 根据deptId获取当前对象
     * @param deptId
     * @return
     */
    @RequestMapping("/getOne")
    public ResultModel getOne(@RequestParam Long deptId){
        SysDept sysDept = deptService.getById(deptId);
        return ResultModel.successed(sysDept);
    }

    /**
     * 根据 parentId获取当前对象
     * @param parentId
     * @return
     */
    @RequestMapping("/getParentId")
    public ResultModel getParentId(Long parentId){
        SysDept sysDept = deptService.getById(parentId);
        return ResultModel.successed(sysDept);
    }

    /**
     * 根据deptId获取部门数据
     * @param parentName
     * @return
     */
    @RequestMapping("/selectName")
    public ResultModel selectName(String parentName){
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("dept_name",parentName);
        SysDept sysDept = deptService.getOne(queryWrapper);
        return ResultModel.successed(sysDept);
    }

    /**
     * 根据当前部门deptId获取该部门下的所有列表 并找出order_num为最大值的数据
     * @param deptId
     * @return
     */
    @RequestMapping("/orderNum")
    public ResultModel orderNum(Long deptId){
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("parent_id",deptId);
        List<SysDept> sysDeptList = deptService.list(queryWrapper);
        if(null == sysDeptList || sysDeptList.size() == 0){
            return ResultModel.successed(1);
        }
        // List根据排序字段进行升序排序
        sysDeptList.sort(Comparator.comparing(SysDept::getOrderNum));
        // 获取当前List最后一位数据的值
        SysDept sysDept = sysDeptList.get(sysDeptList.size() - 1);
        return ResultModel.successed(sysDept.getOrderNum() + 1);
    }


    /**
     * 查询部门名称
     * @param deptName
     * @return
     */
    @RequestMapping("/getName")
    public ResultModel getName(String deptName){
        QueryWrapper wrapper = new QueryWrapper<>();
        wrapper.eq("dept_name", deptName);
        wrapper.eq("del_flag","0");
        SysDept one = deptService.getOne(wrapper);
        if (one != null) {
            return ResultModel.failed(-100,"部门名称已存在");
        }
        return ResultModel.successed(null);
    }
    /**
     * 添加或修改部门
     * @param sysDept
     * @return
     */
    @RequestMapping("/saveOrUpdate")
    public ResultModel saveOrUpdate(@RequestBody SysDept sysDept){
        if(sysDept.getDeptId() == null){
            String username = request.getHeader("username");
            sysDept.setCreateBy(username);
            sysDept.setCreateTime(new Date());
            QueryWrapper queryWrapper = new QueryWrapper();
            // 根据当前父部门名称获取父部门对象
            queryWrapper.eq("dept_name",sysDept.getParentName());
            SysDept dept = deptService.getOne(queryWrapper);
            // 赋值
            sysDept.setAncestors(dept.getAncestors() + "," + sysDept.getParentId());
            deptService.save(sysDept);
            return ResultModel.successed("添加成功");
        }else{
            String username = request.getHeader("username");
            sysDept.setUpdateBy(username);
            sysDept.setUpdateTime(new Date());
            deptService.updateById(sysDept);
            return ResultModel.successed("修改成功");
        }
    }

    /**
     * 删除部门
     * @param deptId
     * @return
     */
    @RequestMapping("/del")
    public ResultModel del(@RequestParam Long deptId){
        SysDept dept = deptService.getById(deptId);
        QueryWrapper queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("parent_id",dept.getDeptId());
        List<SysDept> sysDeptList = deptService.list(queryWrapper);
        System.out.println(sysDeptList);
        if(sysDeptList != null){
            for (SysDept sysDept : sysDeptList) {
                if("0".equals(sysDept.getDelFlag())){
                    return ResultModel.failed(-200, "部门存在子部门,不允许删除");
                }else{
                    System.out.println("跳出去删除");
                    break;
                }
            }
        }
        dept.setDelFlag("2");
        deptService.updateById(dept);
        System.out.println("删除成功");
        return ResultModel.successed(null);
    }
    @GetMapping("/getFactoryList/{deptId}")
    public Result<List<SysDept>> getFactoryList(@PathVariable("deptId") Integer deptId){
        List<SysDept> list=deptService.getFactoryList(deptId);
        return Result.ok(list);
    }
}
